package com.anssy.voteballot.http;

import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class LoggingInterceptor implements Interceptor {

    private String TAG = "LoggingInterceptor";
    private static final Charset UTF8 = Charset.forName("UTF-8");


    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        request = request.newBuilder()
//                .addHeader("Home-Token", SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).getString(ConstantValue.SP_TOKEN))
                .build();
        RequestBody requestBody = request.body();

        String body = null;

        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            body = buffer.readString(charset);
        }

        LogUtils.v("发送请求\nmethod：%s\nurl：%s\nheaders: %sbody：%s",
                request.method(), request.url(), request.headers(), body);

        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        String rBody = null;

        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                e.printStackTrace();
            }
        }
        rBody = buffer.clone().readString(charset);

        LogUtils.v("收到响应 %s%s %ss\n请求url：%s\n请求body：%s\n响应body：%s",
                response.code(), response.message(), tookMs, response.request().url(), body, rBody);
//                response.code(), response.message(), tookMs, response.request().url(), body, rBody);

        return response;
    }

/*    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
//                    .addHeader("token", SPUtils.getInstance(SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).getString(ConstantValue.SP_TOKEN))
//                .addHeader("appType", CommonInfo.app_type)

                .addHeader("token", SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).getString(ConstantValue.SP_TOKEN))
//                .addHeader("version", CheckUtil.getVersion())
                .build();

//        request = request.newBuilder()
//                .addHeader("appType", "fcz")
//                .build();

        long t1 = System.nanoTime();
        LogUtils.v(TAG, String.format("请求参数---url = %s, \r\n " +
                        "method = %s, \r\n " +
                        "connection = %s, \r\n " +
                        "request headers = %s",
                request.url(),
                request.method(),
                chain.connection(),
                request.headers()));

        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();

        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }

        if (responseBody.contentLength() != 0) {
            //logger.log("");
            //logger.log(buffer.clone().readString(charset));
            LogUtils.v(TAG, "响应内容:" + buffer.clone().readString(charset));
        }
        //L.e(proceed.networkResponse().body().string());
        //L.e(proceed.body().string());


        long t2 = System.nanoTime();
        LogUtils.v(TAG, String.format("response for %s ," +
                        //"receive time = %.f ms , " +
                        "header = %s",
                response.request().url().toString(),
                //(t2-t1)/1e6d,
                response.headers()));

        return response;
    }*/
}
